// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require(CONFIG.BasePath + "js/enterprise/base");
	var router = require("../hash/pageRouter");
	var constant = require("constant");
	var css_pickup = require("./documentSign.css");
	var databind = require("databind");
	var media = require("media");
	var validator = require("validate");
	var financeId;
	var financeState;
	var contractType;
	var inventoryId = [];
	var remark;
	var tools = require("tools");
	var caseSizeMap = new tools.Map();
	var storage = window.sessionStorage; 
	var html_savePos = require("./html_savePosInfo.html");
	var html_signAll = require("./html_signAll.html");
	var html_signFileSealList = require("./html_signFileSealList.html");
	var html_signCallback = require("./html_signCallback.html");
	var ii;
	var ii1;
	var ii2;
	var record;

	var init = function(page) {
		financeId = storage.getItem("financeId");
		financeState=page.params.financeState;
		contractType=2;
		if(financeId==null){
			financeId = page.params.financeId;
		}else{
			storage.removeItem("financeId");
		}
		if(financeState != 24){
			$(".pickupForm p").remove();
			$(".submit-document").remove();
			$(".documentSignTitle").remove();
			$(".completeSign").remove();
			$(".signAll").remove();
			$("input[type=checkbox]").remove();
		}
		
		router.init();
		initEvent();
	};

	var initEvent = function() {
		if (base.getData("sid") == null) {
			location.href = "../login/login.html";
		}
		
		inquireFinanceContract();
		
		$("#documentSignList").on("click", ".sign", function(){
			var $this = $(this);
			window.open("../app/index.htm?financeId=" + financeId + "&financeState=" + financeState + "&fileUuid=" + $this.parents("tr").attr("fileUuid"));
		});
		
		//查看签署记录
		$("#documentSignList").on("click", ".showSignRecord", function(){
			var $this = $(this);
			
			layer.open({
			  type: 1,
			  title: "签章记录",
			  skin: 'layui-layer-rim', //加上边框
			  area: ['820px', '500px'], //宽高
			  content: html_signFileSealList,
			  btn: ['确定']
			});
			
			tools.loadList("inquireSignFileSealInfoPageList.json", $(".signFileSealList table"), $(".signFileSealList script"), {"fileUuid": $this.parents("tr").attr("fileUuid")}, function(){
				
			}, $(".signFileSealList .pagerCon"));
			
			$(".signFileSealList .cancelPos").unbind("click").click(function(){
				var $this1 = $(this);
				//询问框
				ii2 = layer.confirm('是否确认取消该签章', {
				  btn: ['确定','取消'] //按钮
				}, function(){
				  cancelSealPos($this1.parents("tr").attr("signFileSealId"), $this.parents("tr").attr("fileUuid"));
				}, function(){
				  
				});
			});
		});
		
		
		$("#documentSignList .signAll").unbind("click").click(function(){
			
//			var flag = true;
//			$.each($(".checks"), function(){
//				var $this = $(this);
//				if ($this.attr("disabled") != "disabled") {
//					$this.parents("table").find("tr").css("background-color", "#FFF");
//					$this.parents("tr").css("background-color", "pink");
//					flag = false;
//					base.alert(2, "还有文件尚未签署!");
//					return false;
//				}
//			});
//			if (flag) {
//				submitCustomerFinanceContract(financeId);
//				return;
//			}
			
			var filesInfoIds = [];
			var fileUuids = [];
			record = true;
			$.each($("#documentSignList .checks:checked"), function() {
				var $this = $(this);
				
				if ($this.parents("tr").attr("signState") == "0") {
					filesInfoIds.push($this.parents("tr").attr("filesInfoId"));
					fileUuids.push($this.parents("tr").attr("fileUuid"));
					
					inquireSignFileSealInfoPageList($this.parents("tr").attr("fileUuid"));
					if (record == false) {
						$this.parents("table").find("tr").css("background-color", "#FFF");
						$this.parents("tr").css("background-color", "pink");
						return false;
					}
				}
				
			});
			
			if (record == false) {
				base.alert(2, "还有合同尚未签章！");
				return;
			}
			
			if (0 == filesInfoIds.length || 0 == fileUuids.length) {
//				base.alert(2, "请勾选需要签署的文件！");
				submitCustomerFinanceContract(financeId);
				return;
			}
			
			ii1 = layer.open({
			  type: 1,
			  title: "提示",
			  skin: 'layui-layer-rim', //加上边框
			  area: ['420px', '245px'], //宽高
			  content: html_signAll,
			  btn: ['签署', "取消"],
			  yes: function(){
			  	var promptDialog = validator.validateInput($(".signAll"));
				if (promptDialog.length != 0) {
					base.alert(3, promptDialog);
					return
				}
			  	createEnterpriseDocumentSummarySignAll(filesInfoIds, fileUuids, 2, $("#main .mobile").html(), $(".signAll input[name=code]").val());
			  } 
			});
			
			$(".signAll input[name=mobile]").val($("#main .mobile").html().replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'));
			
			tools.countDown($(".getCode"), "获取验证码", true);
			$(".getCode").unbind("click").click(function(){
				sendSignCode3rd($("#main .mobile").html());
			});
			
			
		});
		
//		$(".completeSign").unbind("click").click(function(){
//			var flag = true;
//			$.each($(".checks"), function(){
//				var $this = $(this);
//				if ($this.attr("disabled") != "disabled") {
//					$this.parents("table").find("tr").css("background-color", "#FFF");
//					$this.parents("tr").css("background-color", "pink");
//					flag = false;
//					base.alert(2, "还有文件尚未签署!");
//					return false;
//				}
//			});
//			if (flag) {
//				submitCustomerFinanceContract(financeId);
//			}
//		});
	};
	
	//获取E签宝验证码
	var sendSignCode3rd =function(mobile){
		base.fnAjax({
			action : "sendSignCode3rd.json",
			async : false, // 同步异步
			oData : {
				mobile: mobile
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					tools.countDown($(".getCode"), "获取验证码", false);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};
	
	//取消文件签章位置
	var cancelSealPos =function(signFileSealId, fileUuid){
		base.fnAjax({
			action : "cancelSealPos.json",
			async : false, // 同步异步
			oData : {
				signFileSealId: signFileSealId
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "操作成功");
					layer.close(ii2);
					tools.loadList("inquireSignFileSealInfoPageList.json", $(".signFileSealList table"), $(".signFileSealList script"), {"fileUuid": fileUuid}, function(){
						$(".signFileSealList .cancelPos").unbind("click").click(function(){
							var $this1 = $(this);
							//询问框
							ii2 = layer.confirm('是否确认取消该签章', {
							  btn: ['确定','取消'] //按钮
							}, function(){
							  cancelSealPos($this1.parents("tr").attr("signFileSealId"), $this.parents("tr").attr("fileUuid"));
							}, function(){
							  
							});
						});
					}, $(".signFileSealList .pagerCon"));
				} else {
					base.alert(2, data.message);
				}
			}
		});
	};
	
	//查询文件印章信息
	var inquireSignFileSealInfoPageList =function(fileUuid){
		base.fnAjax({
			action : "inquireSignFileSealInfoPageList.json",
			async : false, // 同步异步
			oData : {
				fileUuid: fileUuid,
				signState: 0
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					if (data.datas.length == 0) {
						record = false;
					}
				} else {
					base.alert(2, data.message);
				}
			}
		});
	}
	
	//完成签署
	var submitCustomerFinanceContract =function(financeId){
		base.fnAjax({
			action : "submitCustomerFinanceContract.json",
			async : false, // 同步异步
			oData : {
				financeId: financeId
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "操作成功！");
//					router.route("account/accountDetail.html?financeId=" + financeId);
					router.route("account/documentSign.html?financeId=" + financeId+"&financeState=23");
				} else {
					base.alert(2, data.message);
				}
			}
		});
	}
	
	var createEnterpriseDocumentSummarySignAll =function(filesInfoId, fileUuid, sealType, mobile, code){
		base.fnAjax({
			action : "createEnterpriseDocumentSummarySignAll.json",
			async : false, // 同步异步
			oData : {
				filesInfoId: filesInfoId,
				fileUuid: fileUuid,
				sealType: sealType,
				mobile: mobile,
				code: code
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					base.alert(1, "签署成功！");
					layer.close(ii1);
					submitCustomerFinanceContract(financeId);
//					router.route("account/documentSign.html?financeId=" + financeId+"&financeState="+financeState);
				} else {
					base.alert(2, data.message);
				}
			}
		});
	}
	
	var inquireFinanceContract = function() {
		base.fnAjax({
			action : "inquireFinanceContract.json",
			async : false, // 同步异步
			oData : {
				financeId : financeId,
				contractType: contractType
			}, // 传递参数
			fnSuccess : function(data) {
				if (data.status == 200) {
					databind.fillForm($("#documentSignList"), data.datas[0]);
					
					$("#documentSignList table").html("<tr><th><input type='checkbox' class='checkAll'></th><th></th><th>文件名称</th><th>文件类型</th><th>状态</th><th>退回原因</th><th>合同修改</th><th>签署记录</th><th>返回信息</th><th style='text-align:center;'>操作</th></tr>")
					var i = 1;
					$.each(data.datas[0].financeFilesInfoList, function() {
						var isSign = this.isSign;
						var filesInfoId = this.filesInfoId;
						var signState = this.fileSignState.split(',');
						var msg = [];
						if (this.msg != null) {
							msg = this.msg.split(',');
						}
						var j = 0;
						var fs1 = this.filesUuid.split(',');
						var ss1 = this.isSign.split(',');
						var fileType = this.normFileName;
//						$.each(this.filesUuid.split(','), function() {
						for (var x = 0; x < fs1.length; x++) {
							var _this = fs1[x];
							if ($.trim(_this) != "") {
								var m = msg[j];
								if (m == null || m == "null") {
									m = "";
								}
								var str;
								if (ss1[x] == '1') {
									if (signState[j] != 0) {
										str = "<tr signState='"+signState[j]+"' fileUuid='"+_this+"' filesInfoId='"+filesInfoId+"' ><td><input checked='checked' disabled='disabled' type='checkbox' class='checks'></td><td>"+i+"</td><td>"+tools.inquireFile(_this)+"</td><td>"+fileType+"</td><td>"+constant.getValueByKey(73, signState[j])+"</td><td><a href='javascript:void(0);' class='callBackDetail'>详情</a></td><td><a href='javascript:void(0);' class='updateDetail'>详情</a></td><td><a href='javascript:void(0);' class='showSignRecord'>查看</td><td>"+m+"</td><td style='text-align:right;'><a target='_blank' href='/finance/api/v1.0/viewPdfFile.json?fileUuid="+_this+"'>预览</a></td></tr>";
									} else {
										str = "<tr signState='"+signState[j]+"' fileUuid='"+_this+"' filesInfoId='"+filesInfoId+"' ><td><input checked='checked' type='checkbox' class='checks'></td><td>"+i+"</td><td>"+tools.inquireFile(_this)+"</td><td>"+fileType+"</td><td>"+constant.getValueByKey(73, signState[j])+"</td><td><a href='javascript:void(0);' class='callBackDetail'>详情</a></td><td><a href='javascript:void(0);' class='updateDetail'>详情</a></td><td><a href='javascript:void(0);' class='showSignRecord'>查看</td><td>"+m+"</td><td style='text-align:right;'><a href='javascript:void(0);' class='sign'>签章</a> <a target='_blank' href='/finance/api/v1.0/viewPdfFile.json?fileUuid="+_this+"'>预览</a> <a href='javascript:void(0);' class='callBack'>退回</a></td></tr>";
									}
								} else {
									str = "<tr signState='"+signState[j]+"' fileUuid='"+_this+"' filesInfoId='"+filesInfoId+"' ><td><input type='checkbox' disabled='disabled'></td><td>"+i+"</td><td>"+tools.inquireFile(_this)+"</td><td>"+fileType+"</td><td>-</td><td><a href='javascript:void(0);' class='callBackDetail'>详情</a></td><td><a href='javascript:void(0);' class='updateDetail'>详情</a></td><td></td><td></td><td style='text-align:right;'><a target='_blank' href='/finance/api/v1.0/viewPdfFile.json?fileUuid="+_this+"'>预览</a></td></tr>";
								}
								if (str != null) {
									$("#documentSignList table").append(str);
									i++;
									str = null;
								}
								m = "";
								j++;
							}
						};
						
						tools.addCheckAllEvent($("#documentSignList .checks"), $("#documentSignList .checkAll"));
					});
					
					//退回
					$(".callBack").unbind("click").click(function(){
						var ii = layer.open({
						  type: 1,
						  title: "退回理由",
						  skin: 'layui-layer-rim', //加上边框
						  area: ['620px', '300px'], //宽高
						  content: html_signCallback,
						  btn: ['确定', '取消'],
						  yes: function(){
						  	databind.submitDom($(".signCallback"), function(){
						  		layer.msg("退回成功！");
						  		layer.close(ii);
						  		inquireFinanceContract();
						  	});
						  }
						});
						
						$("input[name=fileUuid]").val($(this).parents("tr").attr("fileUuid"));
						$("input[name=financeId]").val(financeId);
					});
					
					//退回原因
					$(".callBackDetail").unbind("click").click(function(){
						var fuid = $(this).parents("tr").attr("fileUuid");
						
						var ii = layer.open({
						  type: 1,
						  title: "退回理由",
						  skin: 'layui-layer-rim', //加上边框
						  area: ['620px', '300px'], //宽高
						  content: html_signCallback,
						  btn: ['确定']
						});
						
						$("textarea[name=remark]").attr({"name": "callbackReamrk", "readOnly": "readOnly"}).css("border", "none");
						
						databind.fillInput($(".signCallback"), {
							action: "inquireFinanceFilesInfoDetail.json?fileUuid="+fuid,
							version: "v1.0"
						});
					});
					
					//修改原因
					$(".updateDetail").unbind("click").click(function(){
						var fuid = $(this).parents("tr").attr("fileUuid");
						
						var ii = layer.open({
						  type: 1,
						  title: "合同修改",
						  skin: 'layui-layer-rim', //加上边框
						  area: ['620px', '300px'], //宽高
						  content: html_signCallback,
						  btn: ['确定']
						});
						
						$("textarea[name=remark]").attr({"name": "updateReamark", "readOnly": "readOnly"}).css("border", "none");
						
						databind.fillInput($(".signCallback"), {
							action: "inquireFinanceFilesInfoDetail.json?fileUuid="+fuid,
							version: "v1.0"
						});
					});
					
					if(financeState == 23 || financeState == 22){
						$(".sign").remove();
						$(".callBack").remove();
					}
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	}
	
	return {
		init: init
	};
});